<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { ElForm, ElFormItem, ElInput, ElButton, ElInputNumber, ElTable, ElTableColumn, ElMessage, ElLoading, ElDatePicker, ElSelect, ElOption, ElMessageBox } from 'element-plus'
import axios from 'axios'

const store = useStore()
const form = ref({
  className: '',
  sectionNumber: 1,
  topic: '',
  teacherName: '',
  date: '',
  classroom: ''
})

const loading = ref(false)
const tableLoading = ref(false)
const kickOutLoading = ref(false)
const selectedClassroom = ref('')
const teacherClassroom = ref('') // 教师选择的教室，用于过滤活动会话
const rules = {
  className: [
    { required: true, message: '请输入班级', trigger: 'blur' }
  ],
  sectionNumber: [
    { required: true, message: '请输入节次', trigger: 'blur' }
  ],
  topic: [
    { required: true, message: '请输入课题', trigger: 'blur' }
  ],
  teacherName: [
    { required: true, message: '请输入教师姓名', trigger: 'blur' }
  ],
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  classroom: [
    { required: true, message: '请输入教室', trigger: 'blur' }
  ]
}

const activeSession = computed(() => store.state.activeSession)
const signInRecords = computed(() => store.state.signInRecords)
const isSignInInProgress = computed(() => store.getters.isSignInInProgress)

// 创建签到会话
const createSignInSession = async () => {
  loading.value = true
  try {
    const sessionData = {
      className: form.value.className,
      sectionNumber: form.value.sectionNumber,
      topic: form.value.topic,
      teacherName: form.value.teacherName,
      date: form.value.date,
      classroom: form.value.classroom
    }
    
    const session = await store.dispatch('createSignInSession', sessionData)
    ElMessage.success('签到会话创建成功')
    // 移除自动刷新活动会话，避免覆盖刚创建的会话数据
  } catch (error) {
    ElMessage.error(error.response?.data?.error || '创建签到会话失败')
  } finally {
    loading.value = false
  }
}

// 开始签到
const startSignIn = () => {
  if (!activeSession.value) {
    ElMessage.warning('请先创建签到会话')
    return
  }
  
  loading.value = true
  store.dispatch('startSignIn').then(() => {
    ElMessage.success('签到已开始')
  }).catch(error => {
    ElMessage.error('开始签到失败: ' + (error.message || '未知错误'))
  }).finally(() => {
    loading.value = false
  })
}

// 创建新签到会话（清空当前会话）
const createNewSession = () => {
  // 清空store中的活动会话，使界面切换到创建表单
  store.commit('SET_ACTIVE_SESSION', null)
  ElMessage.info('请创建新的签到会话')
}
const endSignIn = () => {
  if (!activeSession.value) {
    ElMessage.warning('没有进行中的签到会话')
    return
  }
  
  loading.value = true
  store.dispatch('endSignIn').then(() => {
    ElMessage.success('签到已结束')
  }).catch(error => {
    ElMessage.error('结束签到失败: ' + (error.message || '未知错误'))
  }).finally(() => {
    loading.value = false
  })
}

// 刷新签到记录
const refreshSignInRecords = () => {
  if (activeSession.value) {
    tableLoading.value = true
    store.dispatch('querySignInRecords', activeSession.value.id).finally(() => {
      tableLoading.value = false
    })
  }
}

// 踢出学生
const handleKickOut = async (studentName) => {
  try {
    await ElMessageBox.confirm(
      `确定要踢出学生「${studentName}」吗？踢出后该学生将需要重新签到。`,
      '踢出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    kickOutLoading.value = true
    const result = await store.dispatch('kickOutStudent', studentName)
    
    if (result.success) {
      ElMessage.success(result.message)
    } else {
      ElMessage.error(result.message || '踢出失败')
    }
  } catch (error) {
    // 用户取消操作时也会进入catch，但不需要提示
    if (error !== 'cancel') {
      ElMessage.error('踢出失败：' + (error.message || '未知错误'))
    }
  } finally {
    kickOutLoading.value = false
  }
}



// 格式化时间
const formatTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN')
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}年${month}月${day}日`

}

// 按教室筛选后的签到记录
const filteredSignInRecords = computed(() => {
  if (!selectedClassroom.value) {
    return signInRecords.value
  }
  return signInRecords.value.filter(record => record.classroomLocation === selectedClassroom.value)
})

// 查询指定教室的活动会话
const queryActiveSessionByClassroom = () => {
  if (teacherClassroom.value) {
    store.dispatch('queryActiveSessionByClassroom', teacherClassroom.value)
  }
}

// 页面加载时初始化
onMounted(() => {
  // 先不自动查询，等待教师选择教室
})

// 监听教室选择变化
watch(teacherClassroom, (newValue) => {
  if (newValue) {
    queryActiveSessionByClassroom()
    // 同步教室值到创建表单
    form.value.classroom = newValue
  } else {
    // 如果清空了教室选择，清空活动会话
    store.commit('SET_ACTIVE_SESSION', null)
    store.commit('SET_SIGN_IN_RECORDS', [])
    // 清空表单中的教室值
    form.value.classroom = ''
  }
})
</script>

<template>
  <div class="container">
    <div class="page-header">
      <h2>教师控制面板</h2>
    </div>
    
    <!-- 功能菜单 -->
    <div class="menu-bar" style="margin-bottom: 20px; display: flex; gap: 10px;">
      <router-link to="/teacher">
        <ElButton type="primary">当前签到管理</ElButton>
      </router-link>
      <router-link to="/teacher/history">
        <ElButton type="primary">历史签到查询</ElButton>
      </router-link>
    </div>
    
    <div class="card" style="margin-bottom: 30px;">
      <h3>签到管理</h3>
      
      <!-- 教室选择器 -->
      <div class="classroom-selector" style="margin-bottom: 20px;">
        <ElFormItem label="选择教室" style="margin-bottom: 0;">
          <ElSelect v-model="teacherClassroom" placeholder="请选择您所在的教室" style="width: 200px;">
            <ElOption label="东微机室" value="东微机室" />
            <ElOption label="西微机室" value="西微机室" />
          </ElSelect>
          <ElButton type="primary" @click="queryActiveSessionByClassroom" :disabled="!teacherClassroom" style="margin-left: 10px;">
            刷新数据
          </ElButton>
        </ElFormItem>
      </div>
      
      <!-- 签到会话信息 -->
      <div v-if="activeSession" class="session-info" style="margin-bottom: 20px; padding: 15px; background-color: #f5f7fa; border-radius: 4px;">
        <p><strong>日期：</strong>{{formatDate(activeSession.date )}}</p>
        <p><strong>班级：</strong>{{ activeSession.className }}</p>
        <p><strong>节次：</strong>{{ activeSession.sectionNumber }}</p>
        <p><strong>课题：</strong>{{ activeSession.topic }}</p>
        <p><strong>教师姓名：</strong>{{ activeSession.teacherName }}</p>
        <p><strong>教室：</strong>{{ activeSession.classroom }}</p>
        <p><strong>创建时间：</strong>{{ formatTime(activeSession.createTime) }}</p>
        <p><strong>开始时间：</strong>{{ formatTime(activeSession.startTime) }}</p>
        <p><strong>结束时间：</strong>{{ formatTime(activeSession.endTime) || '未结束' }}</p>
        <p><strong>状态：</strong>
          <span v-if="activeSession.status === 0">未开始</span>
          <span v-else-if="activeSession.status === 1" style="color: #67c23a;">进行中</span>
          <span v-else-if="activeSession.status === 2" style="color: #909399;">已结束</span>
        </p>
      </div>
      
      <!-- 创建签到会话表单 -->
      <div v-if="!activeSession">
        <ElForm :model="form" :rules="rules" ref="formRef" label-width="100px">
          <ElFormItem label="班级" prop="className">
            <ElInput v-model="form.className" placeholder="请输入班级" />
          </ElFormItem>
          
          <ElFormItem label="节次" prop="sectionNumber">
            <ElInputNumber v-model="form.sectionNumber" :min="1" :max="10" />
          </ElFormItem>
          
          <ElFormItem label="课题" prop="topic">
            <ElInput v-model="form.topic" placeholder="请输入课题" />
          </ElFormItem>
          
          <ElFormItem label="教师姓名" prop="teacherName">
            <ElInput v-model="form.teacherName" placeholder="请输入教师姓名" />
          </ElFormItem>
          
          <ElFormItem label="日期" prop="date">
            <ElDatePicker
              v-model="form.date"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            />
          </ElFormItem>
          
          <ElFormItem label="教室" prop="classroom">
            <ElSelect v-model="form.classroom" placeholder="请选择教室" style="width: 100%">
              <ElOption label="东微机室" value="东微机室" />
              <ElOption label="西微机室" value="西微机室" />
            </ElSelect>
          </ElFormItem>
          
          <ElFormItem>
            <ElButton type="primary" @click="createSignInSession" :loading="loading" :disabled="!teacherClassroom">
              创建签到会话
            </ElButton>
          </ElFormItem>
        </ElForm>
      </div>
      
      <!-- 签到控制按钮 -->
      <div v-else class="control-buttons" style="display: flex; gap: 10px;">
        <ElButton 
          type="success" 
          @click="startSignIn" 
          :disabled="!teacherClassroom || isSignInInProgress"
          :loading="loading"
        >
          开始签到
        </ElButton>
        <ElButton 
          type="warning" 
          @click="endSignIn" 
          :disabled="!teacherClassroom || !isSignInInProgress"
          :loading="loading"
        >
          结束签到
        </ElButton>
        <ElButton 
          type="primary" 
          @click="createNewSession" 
          :loading="loading"
          :disabled="!teacherClassroom"
          v-if="!isSignInInProgress"
        >
          新签到
        </ElButton>
        <ElButton 
          type="primary" 
          @click="refreshSignInRecords" 
          :loading="tableLoading"
          :disabled="!teacherClassroom"
        >
          刷新记录
        </ElButton>

      </div>
    </div>
    
    <!-- 签到学生列表 -->
    <div class="card">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>签到学生列表（共{{ filteredSignInRecords.length }}人）</h3>
        <!-- <ElSelect v-model="selectedClassroom" placeholder="按教室筛选" style="width: 200px;">
          <ElOption label="全部教室" value="" />
          <ElOption label="东微机室" value="东微机室" />
          <ElOption label="西微机室" value="西微机室" />
        </ElSelect> -->
      </div>
      <ElTable 
        :data="filteredSignInRecords" 
        style="width: 100%" 
        :loading="tableLoading"
        v-loading="tableLoading"
        element-loading-text="加载中..."
      >
        <ElTableColumn prop="studentName" label="学生姓名" min-width="180" />
        <ElTableColumn prop="classroomLocation" label="教室位置" min-width="120" />
        <ElTableColumn prop="signInTime" label="签到时间" min-width="200">
          <template #default="scope">
            {{ formatTime(scope.row.signInTime) }}
          </template>
        </ElTableColumn>
        <ElTableColumn prop="action" label="操作" width="100" fixed="right">
          <template #default="scope">
            <ElButton 
              type="danger" 
              size="small" 
              @click="handleKickOut(scope.row.studentName)"
              :disabled="!teacherClassroom || !isSignInInProgress || kickOutLoading"
              :loading="kickOutLoading"
            >
              踢出
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      
      <div v-if="signInRecords.length === 0 && !tableLoading" style="text-align: center; padding: 40px; color: #909399;">
        <p>暂无签到记录</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.control-buttons {
  margin-top: 20px;
}

.session-info {
  animation: slideIn 0.3s ease-in-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}
</style>